package cn.fancylab.template.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import cn.fancylab.model.common.GlobalConfig;
import cn.fancylab.util.JsonUtils;
import cn.fancylab.util.StringUtil;
import cn.fancylab.util.VmBaseUtil;

/**
 * @author gebiao(acerge@163.com)
 * @since Jul 10, 2012 10:37:52 PM
 */
public class VmUtils extends VmBaseUtil {
	private List<String> imgPathList;
	private String cssJsPath;
	private String imgPath;
	public String getImgPath() {
		return imgPath;
	}
	public String getCssJsPath() {
		return cssJsPath;
	}
	private String defPath;
	public  String randomPic(String wh, String imgName){
		if(StringUtils.startsWith(imgName,"http")) return imgName;
		if(imgPathList==null || imgPathList.size()==0) return defPath + wh + "/" + imgName;
		if(StringUtils.isBlank(imgName)) imgName = "img/default_head.png";
		int hashcode = Math.abs(imgName.hashCode());
		int i = (hashcode)%(imgPathList.size());
		if(StringUtils.isBlank(wh)) return imgPathList.get(i) + imgName;
		return imgPathList.get(i) + wh + "/" + imgName;
	}
	public void initStatic(String staticPath){
		this.cssJsPath = staticPath;
	}
	public void initImg(GlobalConfig rateConfig, String picPath){
		this.defPath = picPath;
		imgPathList = new ArrayList<>();
		Map<String, String> strRateMap = VmUtils.readJsonToMap(rateConfig.getContent());
		for(String path : strRateMap.keySet()){
			String rate = strRateMap.get(path);
			int j = Integer.valueOf(rate);
			for(int x = 1;x<=j; x++){
				imgPathList.add(path);
			}
		}
		
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	public String getScriptObject(Object modelObject){
		return JsonUtils.writeObjectToJson(modelObject);
	}
	public String getScriptString(String str){
		str = JsonUtils.writeObjectToJson(str);
		return str;
	}

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	public static String getUniqueString(String str, String splitter){
		if(StringUtils.isBlank(str)) return "";
		Set<String> set = new LinkedHashSet<>();
		set.addAll(Arrays.asList(str.split(splitter)));
		return join(set.iterator(), splitter);
	}
	
	public static boolean isValidCaptchaId(String captchaId) {
		if(StringUtils.length(captchaId) != 24) return false;
		return StringUtil.md5(StringUtils.substring(captchaId, 0, 16) + "sk#8Kr", 8).equals(StringUtils.substring(captchaId, 16));
	}
	public static String getRandomCaptchaId() {
		String s = StringUtil.getRandomString(16) ;
		s += StringUtil.md5(s + "sk#8Kr", 8);
		return s;
	}
}
